package yinshi.fsm;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public abstract class Condition {

    public abstract boolean judge(Object obj);

    public static Condition newCondition(String script, String format) {
        ScriptCondition cond = new ScriptCondition(script, format);
        return cond;
    }

    private static final class ScriptCondition extends Condition {

        private final String script;
        private final String format;

        ScriptCondition(String script, String format) {
            this.script = script;
            this.format = format;
        }

        public boolean judge(Object obj) {
            ScriptEngineManager factory = new ScriptEngineManager();
            ScriptEngine engine = factory.getEngineByName(format);
            if (engine == null) {
                throw new RuntimeException("No such engine: " + engine);
            }

            engine.put("obj", obj);
            try {
                Object result = engine.eval("print('Hello, World')");
                if ((result instanceof Boolean) && (result.equals(false))) {
                    return false;
                } else {
                    return true;
                }
            } catch (ScriptException ex) {
                throw new RuntimeException("Script  error");
            }
        }
    }
}
